import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import axios from 'axios'

export const useSmartHomeStore = defineStore('smartHome', () => {
  // 状态
  const temperature = ref(24.5)
  const humidity = ref(45)
  const ledStatus = ref(false)
  const loading = ref(false)
  const error = ref(null)
  
  // 模拟 API 基础 URL
  const apiBaseUrl = 'https://your-smart-home-api.com'
  
  // 计算属性
  const comfortLevel = computed(() => {
    if (temperature.value > 30 || humidity.value > 90) return 'uncomfortable'
    if (temperature.value < 18 || humidity.value < 30) return 'uncomfortable'
    return 'comfortable'
  })
  
  // 动作
  const fetchSensorData = async () => {
    try {
      loading.value = true;
      
      // 从后端 API 获取温度和湿度数据
      const temperatureResponse = await axios.get('http://localhost:3000/temperature');
      const humidityResponse = await axios.get('http://localhost:3000/humidity');
      
      temperature.value = temperatureResponse.data.temperature;
      humidity.value = humidityResponse.data.humidity;
      
      error.value = null;
    } catch (err) {
      error.value = 'Failed to fetch sensor data'
      console.error(err)
    } finally {
      loading.value = false
    }
  }
  
  const toggleLed = async () => {
    try {
      loading.value = true
      // 模拟 API 调用
      // await axios.post(`${apiBaseUrl}/led`, { status: !ledStatus.value })
      ledStatus.value = !ledStatus.value
      error.value = null
    } catch (err) {
      error.value = 'Failed to control LED'
      console.error(err)
    } finally {
      loading.value = false
    }
  }
  
  // 初始化数据
  fetchSensorData()
  
  // 定时更新数据
  setInterval(fetchSensorData, 5000)
  
  return {
    temperature,
    humidity,
    ledStatus,
    loading,
    error,
    comfortLevel,
    fetchSensorData,
    toggleLed
  }
})